package user.view;

import static org.math.array.DoubleArray.increment;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.text.JTextComponent;

import model.doe.BifocalLens;
import model.util.FourerExecutor;
import model.util.FourerExecutor.DoeType;

import system.activity.MainListener;
import system.elements.ControlTextField;
import system.util.PlotBuilder;

public class BifocalLensImpl extends Controls {

	private javax.swing.JLabel firstFocusLabel;
	private ControlTextField firstFocusText;
	private javax.swing.JButton cancelButton;
	private javax.swing.JLabel descrLabel;
	private ControlTextField descrText;
	private javax.swing.JLabel secondFocusLabel;
	private ControlTextField secondFocusText;
	private javax.swing.JButton okButton;
	private javax.swing.JLabel radLabel;
	private ControlTextField radText;
	private javax.swing.JLabel wlLabel;
	private ControlTextField wlText;
	private javax.swing.JCheckBox withoutLens;

	private javax.swing.JCheckBox phase;
	private javax.swing.JCheckBox signPhase;
	private javax.swing.JCheckBox fourer;

	public BifocalLensImpl(final MainListener listener) {
		this.listener = listener;
		this.setLayout(new java.awt.BorderLayout());

		init();
	}

	public BifocalLensImpl(final MainListener listener, ArrayList<String> params)
	{
		this.listener = listener;
		this.setLayout(new java.awt.BorderLayout());
		initFromHistory(params);
	}
	
	@Override
	public LinkedList<JTextComponent> elementsQueue()
	{
		LinkedList<JTextComponent> result = new LinkedList<JTextComponent>();
		result.add(radText);
		result.add(firstFocusText);
		result.add(secondFocusText);
		result.add(wlText);
		result.add(descrText);
		return result;
	}
	
	@Override
	protected void init() {
		radLabel = new javax.swing.JLabel();
		radText = new ControlTextField();
		firstFocusLabel = new javax.swing.JLabel();
		firstFocusText = new ControlTextField();
		secondFocusText = new ControlTextField();
		wlText = new ControlTextField();
		descrText = new ControlTextField();
		secondFocusLabel = new javax.swing.JLabel();
		wlLabel = new javax.swing.JLabel();
		descrLabel = new javax.swing.JLabel();
		
		okButton = new javax.swing.JButton();
		cancelButton = new javax.swing.JButton();
		
		withoutLens = new javax.swing.JCheckBox();
		phase = new javax.swing.JCheckBox();
		signPhase = new javax.swing.JCheckBox();
		fourer = new javax.swing.JCheckBox();

		radLabel.setText("Радиус апертуры"); // NOI18N
		radText.setText("6.4"); // NOI18N
		secondFocusLabel.setText("Фокальное расстнояние 2"); // NOI18N
		secondFocusText.setText("200.0"); // NOI18N
		firstFocusText.setText("220.0"); // NOI18N
		wlText.setText("0.063"); // NOI18N
		descrText.setText("0.025"); // NOI18N
		firstFocusLabel.setText("Фокальное расстнояние 1"); // NOI18N
		wlLabel.setText("Длина волны (мкм)"); // NOI18N
		descrLabel.setText("Шаг дескретизации"); // NOI18N
		okButton.setText("Рассчитать"); // NOI18N
		cancelButton.setText("Закрыть"); // NOI18N
		withoutLens.setText("Рассчет с линзой");

		phase.setText("Расчет фазы");
		signPhase.setText("Расчет знака фазы");
		fourer.setText("Выполнить преобразование Фурье");

		fourer.setEnabled(false);
		phase.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				checkFourerAvailable();
			}

		});
		
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(signPhase)
                    .addComponent(phase)
                    .addComponent(withoutLens)
                    .addComponent(fourer)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(descrLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(radLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                            .addComponent(firstFocusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(secondFocusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(wlLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(descrText, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(wlText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(secondFocusText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(firstFocusText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(radText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radLabel)
                    .addComponent(radText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(firstFocusLabel)
                    .addComponent(firstFocusText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(secondFocusLabel)
                    .addComponent(secondFocusText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wlLabel)
                    .addComponent(wlText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(descrLabel)
                    .addComponent(descrText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(withoutLens)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(phase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(signPhase)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fourer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 114, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );
		okButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				try {
					okButton.setEnabled(false);
					final BifocalLens bifocalLens = new BifocalLens(Double
							.parseDouble(radText.getText()), Double
							.parseDouble(firstFocusText.getText()), Double
							.parseDouble(secondFocusText.getText()), Double
							.parseDouble(wlText.getText()), Double
							.parseDouble(descrText.getText()), !withoutLens
							.isSelected());
					listener.clearImagePanel();
					listener.setLoadStatus();
					java.awt.event.ActionListener actionListener = new java.awt.event.ActionListener() {
						public void actionPerformed(
								java.awt.event.ActionEvent actionEvent) {
							try {
								if (phase.isSelected()) {
									
									listener.addImagePanel(bifocalLens
											.getPhaseTo2PiMImage(),
											"Распределение фазы");
								}
								if (signPhase.isSelected()) {
									listener.addImagePanel(bifocalLens
											.getSignPhaseImage(),
											"Распределение знака фазы");
								}
								if (phase.isSelected() && fourer.isSelected()) {
									FourerExecutor fourer = new FourerExecutor();
									ArrayList<BufferedImage> fourerImages = fourer.fft(bifocalLens, DoeType.PHASE);
									listener.addImagePanel(fourerImages.get(0),"Распредление амплитуды после преобразования Фурье");
									
									double[][] z = fourer.getResultAmpl();
									double[] x = increment(0d, 1d, z[0].length);
									double[] y = increment(0d, 1d, z.length);
									String plotDescription = "Распределение амплитуды после преобразования Фурье - график";
									listener.addFastPlotPanel(PlotBuilder.buildFast3DPlot(x, y, z, plotDescription), "Распределение амплитуды после преобразования Фурье - график");
									
									
									listener.addImagePanel(fourerImages.get(1),"Распредление фазы после преобразования Фурье");
									onResize();
									listener.needRepaint();
								}
								onResize();
								listener.needRepaint();
								listener.removeLoadStatus();
								okButton.setEnabled(true);
							} catch (OutOfMemoryError ex) {
								listener.removeLoadStatus();
								okButton.setEnabled(true);
								listener.showErrorMessage("Переполнение памяти");
							}
							catch(IllegalArgumentException ex)
							{
								listener.removeLoadStatus();
								okButton.setEnabled(true);
								listener.showErrorMessage(ex.getMessage());
							}
						}
					};
					Timer timer = new Timer(500, actionListener);
					timer.setRepeats(false);
					timer.start();
				} catch (NumberFormatException ex) {
					listener.showErrorMessage("Ошибка формата входных данных");
					listener.removeLoadStatus();
					okButton.setEnabled(true);
				}
			}
		});
		cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				listener.removeLeftPanel();
				onResize();
				listener.needRepaint();
			}
		});
		Border border = BorderFactory.createEtchedBorder(Color.white,
				new Color(178, 178, 178));
		this.setBorder(border);
		listener.addPanel(this);
		this.show();
	}

	void onResize() {
		this.show();
	}

	@Override
	public void setListener(MainListener listener) {
		this.listener = listener;
	}

	@Override
	public Collection<String> getControlsValues() {
		Date date = new Date();
		Collection<String> result = new ArrayList<String>();
		result.add("                                                                                 "
				+ date.getHours()
				+ ":"
				+ date.getMinutes()
				+ ":"
				+ date.getSeconds()
				+ "   "
				+ date.getDate()
				+ "."
				+ (date.getMonth() + 1) + "." + (date.getYear() + 1900));
		result.add("Бифокальная линза");
		result.add("Введенные параметры:");
		result.add(radLabel.getText() + " = " + radText.getText());
		result.add(firstFocusLabel.getText() + " = " + firstFocusText.getText());
		result.add(secondFocusLabel.getText() + " = "
				+ secondFocusText.getText());
		result.add(wlLabel.getText() + " = " + wlText.getText());
		result.add(descrLabel.getText() + " = " + descrText.getText());
		result.add("");
		return result;
	}
	@Override
	String getClassName()
	{
		return this.getClass().getCanonicalName();
	}
	private void checkFourerAvailable() {
		fourer.setEnabled(phase.isSelected());
		if(fourer.isEnabled() == false)
		{
			fourer.setSelected(false);
		}
	}
}
